package com.jacobson.huobi.utils

import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.huobi.common.expansion.toHex
import java.security.MessageDigest
import java.util.*

/**
 * ================================================
 *
 *  @author Wucz on 2018/8/7 11:18
 * ================================================
 */
object EncryptUtil {
    private const val ALGORITHM_SHA1 = "SHA-1"
    private const val ALGORITHM_MD5 = "MD5"

    fun encryptPassword(telephone: String, password: String): String {
        return telephone.takeIf { telephone.length >= 4 }?.let {
            md5(it.substring(it.length - 4) + password)
        } ?: ""
    }

    fun sha1(input: String): String {
        return encrypt(input, ALGORITHM_SHA1)
    }

    private fun md5(input: String): String {
        val result = encrypt(input, ALGORITHM_MD5).toUpperCase(Locale.getDefault())
        LoggerFactory.getLogger().i("MD5: INPUT: $input, result: $result")
        return result
    }

    private fun encrypt(input: String, algorithm: String): String {
        return MessageDigest.getInstance(algorithm).digest(input.toByteArray(Charsets.UTF_8)).toHex()
    }

    /**
     * 数据加密  sha256 + rsa
     */
    public fun encrypData(data : String, checkCode : String): String {
        val shaEncryp = SHAUtil.getSHA256(data).toUpperCase(Locale.getDefault())
        if (shaEncryp.isNullOrBlank()) {
            return ""
        }
        val rsaEncryp = RSAUtil().encryptByPublicKey(shaEncryp + "#" + checkCode).toUpperCase(Locale.getDefault())
        if (rsaEncryp.isNullOrBlank()) {
            return ""
        }
        return rsaEncryp

    }

}